import json
from dashopt import settings
from django.http import JsonResponse
from django.views import View
from utils.baseview import BaseView
from django.core.cache import caches
from user.models import UserProfile
from goods.models import SKU, SKUImage, SPUSaleAttr
CART_CACHE = caches['carts']


# Create your views here.
class CartsView(BaseView):
    def post(self, request, username):
        """
            添加购物车视图[sku_id | count]
            检查上下架状态
            检验库存
            存入redis数据库
            组织数据返回
            user_id:{
                "sku_id1":[5, 1],
                "sku_id2":[15, 0],
            }
        """
        data = request.data
        sku_id = data.get("sku_id")
        count = int(data.get("count"))
        # 上下架状态[sku-is_launched]
        try:
            sku = SKU.objects.get(id=sku_id, is_launched=True)
        except Exception as e:
            return JsonResponse({"code": 30101, "error": " 商品已下架"})
        # 库存[sku-stock]
        if count > sku.stock:
            return JsonResponse({"code":30103, "error": f"购买数量超过库存,剩余{sku.stock}"})
        # 获取用户的所有购物车数据
        user = request.myuser
        cache_key = self.get_cache_key(user.id)
        carts_Data = self.get_carts_all_data(cache_key)
        # 数据合并
        if not carts_Data:
            li = [count, 1]
        else:
            if carts_Data.get(sku_id):
                new_count = carts_Data.get(sku_id)[0] + count
                if new_count > sku.stock:
                    return JsonResponse({"code":30103, "error": f"购买数量超过库存,剩余{sku.stock}，请尽快购买"})
                li = [new_count, carts_Data.get(sku_id)[0]]
            else:
                li = [count, 1]
        # 入库
        carts_Data[sku_id] = li
        CART_CACHE.set(cache_key, carts_Data)
        result = {
            "code": 200,
            "data": {
                "carts_count": len(carts_Data)
            },
            "base_url": settings.PIC_URL
        }
        return JsonResponse(result)

    def get(self, request, username):
        """
            {
                'code': 200, 
                'data': skus_list, 
                'base_url': PIC_URL
            }

              sku_lists =  [
            {
                "id":"",
                "name":"",
                "count":"",
                "selected":"",
                "default_image_url":"",
                "price":"",
                "sku_sale_attr_name":[],
                "sku_sale_attr_val":[]
            },
            {"":""...}
        ]

        """
        user = request.myuser
        sku_lists = self.get_carts_list(user.id)
        result = {"code":200, "data": sku_lists, "base_url": settings.PIC_URL}
        return JsonResponse(result)
   
    def delete(self, request, username):
        """
            删除购物车中的数据
        """
        data = request.data
        user = request.myuser
        if not user.id:
            return JsonResponse({"code": 30104, "error": "未找到用户"})
        cache_key = self.get_cache_key(user.id)
        cache_data = self.get_carts_all_data(cache_key)
        del cache_data[str(data.get("sku_id"))]
        CART_CACHE.set(cache_key, cache_data)
        result = {
            'code': 200, 
            'data': 
            {
                'carts_count': len(cache_data)
            },
            'base_url': settings.PIC_URL
        }
        return JsonResponse(result)
    def put(self, request, username):
        data = request.data
        user = request.myuser
        if not user.id:
            return JsonResponse({"code": 30104, "error": "未找到用户"})
        cache_key = self.get_cache_key(user.id)
        cache_datas = self.get_carts_all_data(cache_key)
        if data.get("state") == "select" or data.get("state") == "unselect":
            cache_datas = self.select_cart(data, cache_datas)
        elif data.get("state") == "selectall" or data.get("state") == "unselectall":
            cache_datas = self.select_cart_all(data, cache_datas)
        elif data.get("state") == "del" or data.get("state") == "add":
            cache_datas = self.delete_all_cart(data, cache_datas)
        CART_CACHE.set(cache_key, cache_datas)
        sku_lists = []
        for key, value in cache_datas.items():
            sku_list = {}
            sku_list['id'] = key
            sku_data = SKU.objects.get(id=key)
            sku_list['name'] = sku_data.name
            sku_list['count'] = value[0]
            sku_list['select'] = value[1]
            sku_list['default_image_url'] = str(sku_data.default_image_url)
            sku_list['price'] = sku_data.price
            # 销售属性值的id列表和name列表
            attr_value_query = sku_data.sale_attr_value.all()
            sku_list['sku_sale_attr_val'] = [i.name for i in attr_value_query]
            # 销售属性名的id列表和name列表
            attr_name_query = SPUSaleAttr.objects.filter(spu=sku_data.spu)
            sku_list['sku_sale_attr_name'] = [i.name for i in attr_name_query]
            sku_lists.append(sku_list)
        result = {"code":200, "data": sku_lists, "base_url": settings.PIC_URL}
        return JsonResponse(result)
    def get_carts_list(self, user_id):
        cache_key = self.get_cache_key(user_id)
        data = self.get_carts_all_data(cache_key)
        sku_lists = []
        for key, value in data.items():
            sku_list = {}
            sku_list['id'] = key
            sku_data = SKU.objects.get(id=key)
            sku_list['name'] = sku_data.name
            sku_list['count'] = value[0]
            sku_list['select'] = value[1]
            sku_list['default_image_url'] = str(sku_data.default_image_url)
            sku_list['price'] = sku_data.price
            # 销售属性值的id列表和name列表
            attr_value_query = sku_data.sale_attr_value.all()
            sku_list['sku_sale_attr_val'] = [i.name for i in attr_value_query]
            # 销售属性名的id列表和name列表
            attr_name_query = SPUSaleAttr.objects.filter(spu=sku_data.spu)
            sku_list['sku_sale_attr_name'] = [i.name for i in attr_name_query]
            sku_lists.append(sku_list)
        return sku_lists
    def select_cart(self, data, cache_datas):
        select = 1 if data.get("state") == "select" else 0
        sku_id = str(data.get("sku_id"))
        select_data = cache_datas.get(sku_id)
        cache_data = [select_data[0], select]
        cache_datas[sku_id] = cache_data
        return cache_datas
    
    def select_cart_all(self, data, cache_datas):
        flag = 1 if data.get("state") == "selectall" else 0
        for key in cache_datas:
            cache_datas[key][-1] = flag
        return cache_datas

    def delete_all_cart(self, data, cache_datas):
        res = 1 if data.get("state") == "add" else -1
        sku_id = data.get("sku_id")
        cache_datas[sku_id][0] += res
        return cache_datas

    def get_cache_key(self, user_id):
        """
            生成key
        """
        return "carts_%s" % user_id  
    def get_carts_all_data(self, cache_key):
        
        """
            获取用户的所有购物车数据
        """
        data = CART_CACHE.get(cache_key)
        return data if data else {}
    def merge_carts(self, offline_data, user_id):
        """
            合并购物车
            offline_data:离线购物车数据
            [{"id":"1",
            "count":"1",
            "name":"蓝色小尺寸",
            "default_image_url":"sku/1_CWVre0U.png",
            "price":181,
            "selected":true,
            "sku_sale_attr_name":["安踏A/尺寸：","安踏A/颜色："],"sku_sale_attr_val":["15寸","蓝色"]}]
            return:购物车中商品种类的数量
        """
        
        cache_key = self.get_cache_key(user_id)
        cache_data = self.get_carts_all_data(cache_key)
        if not offline_data:
            return len(cache_data)
        for item in offline_data:
            sku_id = item.get("id")
            sku_count = int(item.get("count"))
            if sku_id in cache_data.keys():
                sku_data = cache_data[sku_id]
                sku_data = [sku_data[0] + sku_count, sku_data[1]]
            else:
                sku_data = [sku_count, 1 if item.get("selected") else 0]
            cache_data[sku_id] = sku_data
        CART_CACHE.set(cache_key, cache_data)
        return len(cache_data) 
    def get_carts_dict(self, user_id):
        cache_key = self.get_cache_key(user_id)
        cache_datas = self.get_carts_all_data(cache_key)
        result = {}
        for key, val in cache_datas.items():
            if val[-1] == 1:
                result[key] = val
        return result
    def delete_carts_dict(self, user_id):
        cache_key = CartsView().get_cache_key(user_id)
        cache_datas = CartsView().get_carts_all_data(cache_key)
        cache_data = {}
        for key, val in cache_datas.items():
            if val[-1] == 0:
                cache_data[key] = val
        CART_CACHE.set(cache_key, cache_data)
        return len(cache_data)
    
    def get_carts_dicts(self, user_id):
        cache_key = self.get_cache_key(user_id)
        cache_datas = self.get_carts_all_data(cache_key)
        return len(cache_datas)